<template>
  <view class="message-list-container">
    <!-- 选项卡 -->
    <view class="tabs-container">
      <view class="custom-tabs">
        <view
            class="tab-item"
            v-for="(tab, index) in tabsList"
            :key="index"
            :class="{ 'active': currentTab === index }"
            @click="onTabChange(index)"
        >
          <text class="tab-text">{{ tab.name }}</text>
        </view>
      </view>
    </view>

    <!-- 消息列表 -->
    <scroll-view class="message-list" scroll-y>
      <view class="message-item" v-for="(item, index) in messageList" :key="index"
            @click="openChat(item)">
        <!-- 头像 -->
        <view class="avatar-container">
          <image class="avatar" :src="getAvatarUrl(item)" mode="aspectFill"></image>
        </view>

        <!-- 消息内容区域 -->
        <view class="message-content">
          <!-- 发送者信息 -->
          <view class="sender-info">
            <text class="sender-name">{{ getUserName(item) }}</text>
          </view>

          <!-- 消息内容 -->
          <view class="message-text">
            <text class="message-preview">{{ item.info || '' }}</text>
          </view>
        </view>

        <!-- 时间 -->
        <view class="message-time">
          <text class="time-text">{{ item.createTime }}</text>
          <text class="unread-tag" v-if="!isMessageRead(item)">未读</text>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="messageList.length === 0">
        <u-empty text="暂无消息" mode="message" iconSize="200" textSize="30"></u-empty>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import {
  mapGetters
} from 'vuex'

export default {

  data() {
    return {
      statusBarHeight: 0,
      currentTab: 0, // 当前选项卡索引
      tabsList: [
        {name: '我接收的'},
        {name: '我发送的'}
      ],
      messageList: [], // 当前显示的消息列表
      receivedMessages: [], // 我接收的消息
      sentMessages: [] // 我发送的消息
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  onLoad() {
    this.getSystemInfo()
    // 确保用户信息已加载后再获取消息列表
    // this.$nextTick(() => {
    //   this.loadMessageList()
    //   // 初始显示我接收的消息
    //   this.messageList = this.receivedMessages
    // })
  },
  onShow() {
    // 每次进入页面时刷新消息列表
    this.$nextTick(() => {
      this.loadMessageList()
      // 初始显示我接收的消息
      this.messageList = this.receivedMessages
    })
  },

  methods: {
    // 获取系统信息
    getSystemInfo() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 0
    },

    // 加载消息列表
    loadMessageList() {
      // 初始化加载我接收的消息和我发送的消息
      this.loadReceivedMessages()
      this.loadSentMessages()
    },

    // 加载我接收的消息
    loadReceivedMessages() {
      if (!this.userInfo || !this.userInfo.id) {
        console.log('用户信息不完整')
        return
      }

      let params = {
        pageNo: 1,
        operatorCardId: this.userInfo.id, // 接收者_userInfo的id
        operatorOpenId: this.userInfo.openId // 接收者_用户id
      }

      this.$api.getMssdShopMessagelist(params).then(res => {
        if (res.success) {
          this.receivedMessages = res.result.records || []
          // 如果当前选项卡是"我接收的"，更新显示列表
          if (this.currentTab === 0) {
            this.messageList = this.receivedMessages
          }
        } else {
          console.error('加载接收消息失败:', res)
          this.receivedMessages = []
          if (this.currentTab === 0) {
            this.messageList = []
          }
        }
      }).catch(error => {
        console.error('加载接收消息出错:', error)
        this.receivedMessages = []
        if (this.currentTab === 0) {
          this.messageList = []
        }
      })
    },

    // 加载我发送的消息
    loadSentMessages() {
      if (!this.userInfo || !this.userInfo.id) {
        console.log('用户信息不完整')
        return
      }

      let params = {
        pageNo: 1,
        openId: this.userInfo.openId, // 发送者openId
        cardId: this.userInfo.id // 发送者_userInfo的id
      }

      this.$api.getMssdShopMessagelist(params).then(res => {
        if (res.success) {
          this.sentMessages = res.result.records || []
          // 如果当前选项卡是"我发送的"，更新显示列表
          if (this.currentTab === 1) {
            this.messageList = this.sentMessages
          }
        } else {
          console.error('加载发送消息失败:', res)
          this.sentMessages = []
          if (this.currentTab === 1) {
            this.messageList = []
          }
        }
      }).catch(error => {
        console.error('加载发送消息出错:', error)
        this.sentMessages = []
        if (this.currentTab === 1) {
          this.messageList = []
        }
      })
    },

    // 选项卡切换
    onTabChange(index) {
      console.log('切换选项卡:', index)

      // 防止重复点击
      if (this.currentTab === index) {
        return
      }

      this.currentTab = index

      // 切换数据
      this.$nextTick(() => {
        if (index === 0) {
          // 我接收的
          this.messageList = this.receivedMessages || []
          console.log('显示我接收的消息:', this.receivedMessages.length, this.receivedMessages)
        } else if (index === 1) {
          // 我发送的
          this.messageList = this.sentMessages || []
          console.log('显示我发送的消息:', this.sentMessages.length, this.sentMessages)
        }
      })
    },

    // 返回上一页
    goBack() {
      uni.navigateBack()
    },

    // 获取头像URL
    getAvatarUrl(item) {
      if (this.currentTab === 0) {
        // 我接收的消息，显示发送者头像
        return item.head || '/static/img/default-avatar.png'
      } else {
        // 我发送的消息，显示接收者头像
        return item.operatorHead || '/static/img/default-avatar.png'
      }
    },

    // 获取用户昵称
    getUserName(item) {
      if (this.currentTab === 0) {
        // 我接收的消息，显示发送者昵称
        return item.name || '未知用户'
      } else {
        // 我发送的消息，显示接收者昵称
        return item.name || '未知用户'
      }
    },

    // 判断消息是否已读
    isMessageRead(item) {
      return item.status === 1
    },


    // 打开聊天
    openChat(item) {
      let that = this

      // 判断自己的cardId来判断自己的身份
      let dfCardId = item.cardId == this.userInfo.id ? item.operatorCardId : item.cardId
      let dfOpenId = item.cardId == this.userInfo.id ? item.operatorOpenId : item.openId
      let dfName = item.cardId == this.userInfo.id ? item.operatorName : item.name
      let shopId = item.company
      if (item.cardId !== that.userInfo.id) {
        //   说明是我接收的,点开后,标记为已读
        that._updateToReadByShops(item)
      }
      uni.navigateTo({
        url: `/pagesMall/mallCenter/messageDetail?cardId=${dfCardId}&openId=${dfOpenId}&name=${dfName}&shopId=${shopId} `
      })
    },
    //标记为已读
    _updateToReadByShops(item) {
      let that = this
      let params = {
        id: item.id,
      }
      that.$api.updateToReadByShop(params).then(res => {
        if (res && res.success) {
          console.log('标记为已读成功')
          //刷新消息列表
          that.loadMessageList()
        } else {
          console.log('标记为已读失败', res)
        }
      }).catch(error => {
        console.log('标记为已读出错', error)
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.message-list-container {
  //height: 100vh;
  //background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.tabs-container {
  position: relative;
  background: #fff;
  border-bottom: 1rpx solid #f0f2f5;
  padding: 0 32rpx;
}

.custom-tabs {
  display: flex;
  align-items: center;
}

.tab-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24rpx 0;
  transition: all 0.3s ease;

  &:active {
    background: rgba(39, 106, 238, 0.1);
  }
}

.tab-text {
  font-size: 30rpx;
  font-weight: 500;
  color: #666;
  transition: all 0.3s ease;
}

.tab-item.active .tab-text {
  color: #276aee;
  font-weight: 600;
}

.tab-line {
  position: absolute;
  bottom: 0;
  height: 4rpx;
  background: #276aee;
  border-radius: 2rpx;
  transition: all 0.3s ease;
}

.message-list {
  flex: 1;
  //margin-top: 88rpx;
  padding-top: 20rpx;
}

.message-item {
  padding: 30rpx;
  display: flex;
  align-items: flex-start;
  box-shadow: 0 2rpx 0px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:active {
    background-color: #f8f8f8;
    transform: scale(0.98);
  }
}

.avatar-container {
  margin-right: 24rpx;
  flex-shrink: 0;
}

.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50rpx;
  background-color: #f0f0f0;
}

.message-content {
  flex: 1;
  min-width: 0;
  margin-right: 20rpx;
}

.sender-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12rpx;
}

.sender-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.unread-tag {
  font-size: 22rpx;
  color: #fff;
  background-color: #ff4757;
  padding: 2rpx 8rpx;
  border-radius: 10rpx;
  flex-shrink: 0;
}

.message-text {
  display: flex;
  align-items: flex-start;
  min-width: 0;
}

.message-preview {
  font-size: 28rpx;
  color: #666;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  min-width: 0;
  max-width: 100%;
}

.message-time {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-end;
}

.time-text {
  font-size: 24rpx;
  color: #999;
  line-height: 1.2;
}

.unread-tag {
  margin-top: 28rpx;
}

.empty-state {
  padding: 120rpx 40rpx;
  text-align: center;
}

</style>
